package com.fsnbigdata.util;

import io.swagger.annotations.ApiOperation;

import java.lang.reflect.*;
import java.util.Map;

/**
 * Created by zq on 2019/3/20.
 */
public class ReflectUtil {

    public static void reflect(String content,Method method) throws Exception {

        method.setAccessible(true);
        ApiOperation operation = method.getAnnotation(ApiOperation.class);
        if (operation == null) return;
        InvocationHandler invocationHandler = Proxy.getInvocationHandler(operation);
        Field value = invocationHandler.getClass().getDeclaredField("memberValues");
        value.setAccessible(true);
        Map<String, Object> memberValues = (Map<String, Object>) value.get(invocationHandler);
        memberValues.put("notes", content);


    }

    public static Class<?>[] getPeremeterClass(Class obj, String methodName) throws Exception {
        Class<?> clazz = obj;
        Method[] method = clazz.getDeclaredMethods();
        for (Method m : method) {
            /**
             * * 跳过非指定的方法
             */
            if (!m.getName().equals(methodName)) {
                continue;
            }
            // 获取参数类型的数组 里面有参数的个数 和参数的类型
            Class<?>[] peremeters = m.getParameterTypes();
            return peremeters;
        }
        return null;
    }

    /**
     * 修改注解description
     *
     * @param method
     * @param content
     * @throws Exception
     */
    public static void setAnnotationOn(Method method, String content) throws Exception {
        method.setAccessible(true);
        boolean methodHasAnno = method.isAnnotationPresent(ApiOperation.class); // 是否指定类型的注释存在于此元素上
        if (methodHasAnno) {
            // 得到注解
            ApiOperation methodAnno = method.getAnnotation(ApiOperation.class);
            // 修改
            InvocationHandler h = Proxy.getInvocationHandler(methodAnno);
            // annotation注解的membervalues
            Field hField = h.getClass().getDeclaredField("memberValues");
            // 因为这个字段是 private final 修饰，所以要打开权限
            hField.setAccessible(true);
            // 获取 memberValues
            Map<String, String> memberValues = (Map) hField.get(h);
            // 修改 value属性值
            memberValues.put("value", content);

        }
    }


}

